package com.app.gridview;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Build;
import android.os.Bundle;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.CycleInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.RotateAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;
import com.zhihu.matisse.filter.Filter;
import com.zndroid.gridview.GridDroppableLayout;
import com.zndroid.gridview.IImageBean;
import com.zndroid.gridview.inner.drag.CanPreviewItemClickListener;
import com.zndroid.gridview.inner.drag.GridDragFixedLastAdapter;
import com.zndroid.gridview.inner.drag.IDrawer;
import com.zndroid.gridview.inner.drag.IModeType;
import com.zndroid.gridview.inner.drag.OnItemCapturedListener;
import com.zndroid.gridview.inner.drag.OnItemFixedClickListener;
import com.zndroid.gridview.inner.drag.OnItemTriggerListener;

import java.util.ArrayList;
import java.util.List;

/**
 * 发送朋友圈可以仿照这个实现
 * 使用 {@link com.zndroid.gridview.inner.drag.GridDragFixedLastAdapter}
 * */
public class SendMsgActivityV2 extends AppCompatActivity {
    private ImageView backImageView, sendImageView;
    private LinearLayout targetView;
    private ImageView rbTopImageView, rbBottomImageView;
    private TextView tipTextView;

    private GridDroppableLayout layout;
    private GridDragFixedLastAdapter<ImageInfo> adapter;
    private List<ImageInfo> list = new ArrayList<>();

    private int REQUEST_CODE_CHOOSE = 777;
    private int MAX = 9;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_send_msg_v2);

        initStatusBar();

        layout = findViewById(R.id.gdl);
        backImageView = findViewById(R.id.back);
        sendImageView = findViewById(R.id.send);

        targetView = findViewById(R.id.ll_target_view);
        rbTopImageView = findViewById(R.id.iv_rb_top);
        rbBottomImageView = findViewById(R.id.iv_rb_bottom);
        tipTextView = findViewById(R.id.tv_tip);

        backImageView.setOnClickListener(v -> onBackPressed());
        sendImageView.setOnClickListener(v -> {
            for (ImageInfo it: adapter.getFinalResult()) {
                Log.i("hyhy", it.toString());
            }
        });

        initLayout();
    }

    private void initLayout() {
        ImageInfo endImageInfo = new ImageInfo();
        endImageInfo.setResId(R.drawable.ic_gdl_default_add);

        layout.setImageLoader(new GlideImageDisplay());//第一步，指定图片展示引擎

        adapter = new GridDragFixedLastAdapter<ImageInfo>(this, list, layout.getImageLoader());
//        adapter.showDeleteIcon(true);//使用拖拽删除功能
//        adapter.setDeleteIcon(getDrawable(R.drawable.abc_vector_test));
        adapter.setFixedPile(endImageInfo);
        adapter.setAutoDismissFixPile(true);//自动过滤固定桩（默认;true）

        layout.setDragAdapter(adapter);
        layout.setMax(MAX);
        layout.setMode(IModeType.LONG_PRESS);
        layout.setOnItemFixedClickListener(new OnItemFixedClickListener() {
            @Override
            public void onFixedItemClicked(boolean autoDismissFixPile, int position, IImageBean bean, List<? extends IImageBean> realityList) {
                int max = autoDismissFixPile ? (MAX - realityList.size() + 1) : (MAX - realityList.size());
                if (max > 0) {
                    Matisse.from(SendMsgActivityV2.this)
                            .choose(MimeType.ofAll())
                            .countable(true)
                            .maxSelectable(max)
                            .addFilter(new GifSizeFilter(320, 320, 5 * Filter.K * Filter.K))
                            .gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
                            .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                            .thumbnailScale(0.85f)
                            .imageEngine(new GlideEngine())
                            .showPreview(true) // Default is `true`
                            .forResult(REQUEST_CODE_CHOOSE);
                }

                Toast.makeText(SendMsgActivityV2.this, "固定桩被点击：" + position, Toast.LENGTH_SHORT).show();

            }
        });

        layout.setOnItemClickListener(new CanPreviewItemClickListener<ImageInfo>(this, layout, adapter));
        layout.setOnItemCapturedListener(new OnItemCapturedListener() {
            @Override
            public void onItemCaptured(View v, int position) {
                v.setScaleX(1.1f);
                v.setScaleY(1.1f);
                v.setAlpha(0.9f);
            }

            @Override
            public void onItemReleased(View v, int position) {
                v.setScaleX(1f);
                v.setScaleY(1f);
                v.setAlpha(1f);
            }

        });

        layout.setTriggerView(targetView, new OnItemTriggerListener() {
            @Override
            public void onItemHoldUp(View draggedView, int position) {
                targetView.setVisibility(View.VISIBLE);
                tipTextView.setText("拖动到此处删除");
            }

            @Override
            public void onItemHoldReleased(View draggedView, int position) {
                //控制是否已经进入目标区域
                if (isDragIn) {
                    isDragIn = false;
                } else {
                    targetView.setVisibility(View.GONE);
                }
            }

            @Override
            public void onDragInReleased(View draggedView, int position) {
                list.remove(position);
                adapter.notifyDataSetChanged();

                rbCloseAnimation(rbTopImageView);
                rbShakeAnimation(rbBottomImageView, new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {

                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                        targetView.setVisibility(View.GONE);
                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {

                    }
                });
            }

            @Override
            public void onDragIn(View draggedView, int position) {
                isDragIn = true;

                draggedView.setAlpha(0.5f);
                tipTextView.setText("松开即可删除");

                rbOpenAnimation(rbTopImageView);
            }

            @Override
            public void onDragOut(View draggedView, int position) {
                if (isDragIn) {
                    draggedView.setAlpha(0.9f);
                    tipTextView.setText("拖动到此处删除");

                    rbCloseAnimation(rbTopImageView);
                } else {
                    rbTopImageView.clearAnimation();
                }

                isDragIn = false;
            }
        });

        layout.setDrawer(new IDrawer() {
            @Override
            public void onDraw(Canvas canvas, int width, int height) {
                if (!layout.isNoneMode()) {
                    int offsetX = -dip2px(SendMsgActivityV2.this, 14);
                    int offsetY = -dip2px(SendMsgActivityV2.this, -16);
                    //文字绘制于gridview的右下角，并向左，向上偏移14dp。
                    drawTips(canvas, width + offsetX, height + offsetY);
                }
            }
        }, false);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {
            for (String s : Matisse.obtainPathResult(data)) {
                ImageInfo info = new ImageInfo();
                info.setFilePath(s);

                //覆盖图层实现（指定资源）
                info.setCoverId(R.mipmap.common_play);

                list.add(info);
            }

            adapter.notifyDataSetChanged();
        }
    }


    String paintText = "长按排序或删除";
    int textWidth;
    int textHeight;
    StaticLayout tipsLayout;
    private TextPaint mTextPaint;

    private void drawTips(Canvas canvas, int width, int height) {
        if (mTextPaint == null) {
            mTextPaint = new TextPaint();
            mTextPaint.setColor(Color.parseColor("#cccccc"));
            mTextPaint.setTextSize(dip2px(SendMsgActivityV2.this, 12));
            Paint.FontMetrics fontMetrics = mTextPaint.getFontMetrics();
            textHeight = (int) (fontMetrics.bottom - fontMetrics.top) + 1;
            textWidth = (int) mTextPaint.measureText(paintText) + 1;
        }
        width = width - textWidth;
        height = height - textHeight;
        if (tipsLayout == null) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                tipsLayout = StaticLayout.Builder.obtain(paintText, 0, paintText.length(), mTextPaint, width).build();
            } else {
                tipsLayout = new StaticLayout(paintText, mTextPaint, width, Layout.Alignment.ALIGN_NORMAL, 1.5f, 0f, false);
            }
        }
        canvas.translate(width, height);
        tipsLayout.draw(canvas);
    }

    private int dip2px(Context context, float dpValue) {
        final float scale = getScale(context);
        return (int) (dpValue * scale + 0.5f);
    }

    private float getScale(Context context) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return findScale(fontScale);
    }

    private float findScale(float scale){
        if(scale<=1){
            scale=1;
        }else if(scale<=1.5){
            scale=1.5f;
        }else if(scale<=2){
            scale=2f;
        }else if(scale<=3){
            scale=3f;
        }
        return scale;
    }

    private void initStatusBar() {
        //Android全屏返回布局抖动问题
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
            // 获取状态栏高度
            int statusBarHeight = getResources().getDimensionPixelSize(resourceId);
            View rectView = new View(this);
            // 绘制一个和状态栏一样高的矩形，并添加到视图中
            LinearLayout.LayoutParams params
                    = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, statusBarHeight);
            rectView.setLayoutParams(params);
            //设置状态栏颜色（该颜色根据你的App主题自行更改）
            rectView.setBackgroundColor(ContextCompat.getColor(this, R.color.purple_700));
            // 添加矩形View到布局中
            ViewGroup decorView = (ViewGroup) getWindow().getDecorView();
            decorView.addView(rectView);
            ViewGroup rootView = (ViewGroup) ((ViewGroup) this.findViewById(android.R.id.content)).getChildAt(0);
            rootView.setFitsSystemWindows(true);
            rootView.setClipToPadding(true);
        }
    }


    private boolean isDragIn = false;
    private void rbOpenAnimation(View view) {
        view.clearAnimation();

        RotateAnimation animation = new RotateAnimation(0, 30,
                Animation.RELATIVE_TO_SELF, 1f, Animation.RELATIVE_TO_SELF, 1f);
        DecelerateInterpolator interpolator = new DecelerateInterpolator();
        animation.setInterpolator(interpolator);
        animation.setDuration(300);
        animation.setFillAfter(true);
        animation.setRepeatCount(0);

        view.startAnimation(animation);
    }

    private void rbCloseAnimation(View view) {
        view.clearAnimation();

        RotateAnimation animation = new RotateAnimation(30, -0,
                Animation.RELATIVE_TO_SELF, 1f, Animation.RELATIVE_TO_SELF, 1f);
        DecelerateInterpolator interpolator = new DecelerateInterpolator();
        animation.setInterpolator(interpolator);
        animation.setDuration(300);
        animation.setFillAfter(true);
        animation.setRepeatCount(0);

        view.startAnimation(animation);
    }

    private void rbShakeAnimation(View view, Animation.AnimationListener listener) {
        view.clearAnimation();

        Animation translateAnimation = new TranslateAnimation(0, 4, 0, 0);
        translateAnimation.setInterpolator(new CycleInterpolator(3));
        translateAnimation.setRepeatCount(0);
        translateAnimation.setDuration(400);
        translateAnimation.setAnimationListener(listener);

        view.startAnimation(translateAnimation);
    }
}